#include <stdio.h>
#include <stdlib.h>

void josephus_1(int *a, int size, int start, int count)
{
    int i, j, k, *next;
    next = malloc(size * sizeof(int));
    
    for (i = 0; i < size; i++) {
        next[i] = (i+1)%size;
    }

    for (i = 0, j = start-1; i < size; i++, j=next[j])
    {
        for (k = 1; k < count; k++)
            j = next[j];

        printf("%d\n",a[j]);

        for (k = 0; k < size; k++) {
            if (next[k] == j)
                next[k] = next[j];
        }
    }

    free(next);
}

void josephus_2(int *a, int size, int start, int count)
{
    int i, s;

    if (size == 1)
        printf("%d\n", a[0]);

    for (i = 2, s = 0; i <= size; i++) {
        s = (s+count)%i;
    }

    printf("%d\n", a[(s+start-1)%size]);
}

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,9};

    josephus_1(a, sizeof(a)/sizeof(int), 1, 6);

    printf("only for the last: ");
    josephus_2(a, sizeof(a)/sizeof(int), 1, 6);

    return 0;
}
